<template>
  <div class="display-chart-container">
    <SimpleSidebar />
  <div class="user-preferences">
    <el-card class="header-card" shadow="hover">
   <div class="header-content">
    <h1>用户喜好分析</h1>
    <router-link to="/add" class="add-button">新增</router-link>
   </div>
    </el-card>
    <!-- 搜索和筛选区域 -->
    <div class="control-panel">
      <input
          v-model="searchQuery"
          placeholder="搜索用户ID或标签..."
          class="search-input"
      >
      <select v-model="selectedTag" class="tag-filter">
        <option value="">所有标签</option>
        <option v-for="tag in uniqueTags" :key="tag" :value="tag">{{ tag }}</option>
      </select>
      <button @click="sortByPercentage" class="sort-btn">
        {{ sortAscending ? '降序排序' : '升序排序' }}
      </button>
    </div>

    <!-- 数据表格 -->
    <div class="table-container">
      <table>
        <thead>
        <tr>
          <th>用户ID</th>
          <th>标签名称</th>
          <th>喜好占比</th>
          <th>操作</th>
        </tr>
        </thead>
        <tbody>
        <tr v-for="item in filteredData" :key="item.id">
          <td>{{ item.userId }}</td>
          <td>{{ item.tag }}</td>
          <td>
            <div class="percentage-bar-container">
              <div
                  class="percentage-bar"
                  :style="{ width: item.percentage }"
                  :class="getPercentageClass(item.percentage)"
              ></div>
              <span class="percentage-text">{{ item.percentage }}</span>
            </div>
          </td>
          <td class="action-buttons">
            <router-link  
              :to="{name: 'edit', params: {id: item.id} }"
              class="edit-btn">
              编辑
            </router-link>
            <button @click="deleteItem(item.id)" class="delete-btn">删除</button>
            <router-link
                :to="'/stats/' + item.userId"
                class="detail-btn"
            >
              查看详情
            </router-link>
          </td>
        </tr>
        </tbody>
      </table>
    </div>

    <!-- 统计图表 -->
    <div class="chart-container">
      <h3>标签分布统计</h3>
      <div class="chart">
        <div
            v-for="tag in tagStatistics"
            :key="tag.name"
            class="chart-bar"
            :style="{ height: tag.count * 20 + 'px' }"
        >
          <span class="chart-label">{{ tag.name }} ({{ tag.count }})</span>
        </div>
      </div>
    </div>
  </div>
  </div>
</template>

<script>

import SimpleSidebar from "@/views/chart/SimpleSidebar.vue";
import Service from '@/router/interceptor.js'
import { ElMessage } from 'element-plus'

export default {
  name: 'UserPreferences',
  components: {SimpleSidebar},
  data() {
    return {
      preferences: [
        { id: 1, userId: '200001', tag: '科技', percentage: '80%' },
        { id: 2, userId: '200002', tag: '娱乐', percentage: '75%' },
        { id: 3, userId: '200003', tag: '教育', percentage: '67%' },
        { id: 4, userId: '200004', tag: '游戏', percentage: '60%' },
        { id: 5, userId: '200005', tag: '音乐', percentage: '80%' },
        { id: 6, userId: '200006', tag: '体育', percentage: '67%' },
        { id: 7, userId: '200007', tag: '科技', percentage: '55%' },
        { id: 8, userId: '200008', tag: '音乐', percentage: '90%' },
      ],
      newItem: {
        userId: '',
        tag: '科技',
        percentage: ''
      },
      searchQuery: '',
      selectedTag: '',
      sortAscending: false,
      editingId: null
    }
  },
  computed: {
    uniqueTags() {
      return [...new Set(this.preferences.map(item => item.tag))];
    },
    filteredData() {
      let data = [...this.preferences];

      // 搜索过滤
      if (this.searchQuery) {
        const query = this.searchQuery.toLowerCase();
        data = data.filter(item =>
            item.userId.toLowerCase().includes(query) ||
            item.tag.toLowerCase().includes(query)
        );
      }

      // 标签过滤
      if (this.selectedTag) {
        data = data.filter(item => item.tag === this.selectedTag);
      }

      // 排序
      if (this.sortAscending) {
        data.sort((a, b) => parseInt(a.percentage) - parseInt(b.percentage));
      } else {
        data.sort((a, b) => parseInt(b.percentage) - parseInt(a.percentage));
      }

      return data;
    },
    tagStatistics() {
      const stats = {};
      this.preferences.forEach(item => {
        if (!stats[item.tag]) {
          stats[item.tag] = 0;
        }
        stats[item.tag]++;
      });
      return Object.keys(stats).map(tag => ({
        name: tag,
        count: stats[tag]
      })).sort((a, b) => b.count - a.count);
    }
  },mounted() {
    this.loadData(); // 页面加载时加载数据
  },
  methods: {
    async loadData() {
      try {
        const response = await Service.get('/api/userFlavor/loadDataList', {
          params: {
            pageNo: 1,
            pageSize: 999999
          }
        });
        if (response.code === 200 && response.data?.list) {
          // 转换后端数据结构
          this.preferences = response.data.list.map(item => ({
            id: item.id,
            userId: String(item.uid),
            tag: item.tname,
            percentage: `${(item.tpercent * 100).toFixed(0)}%`
          }));
        }
      } catch (error) {
        console.error('数据加载失败，使用模拟数据:', error);
        this.preferences = [/* 保留原有模拟数据 */];
      }
    },
    addItem() {
      if (!this.newItem.userId || !this.newItem.percentage) return;

      if (this.editingId) {
        // 更新现有项
        const index = this.preferences.findIndex(item => item.id === this.editingId);
        if (index !== -1) {
          this.preferences.splice(index, 1, {
            id: this.editingId,
            ...this.newItem
          });
        }
        this.editingId = null;
      } else {
        // 添加新项
        this.preferences.push({
          id: Date.now(),
          ...this.newItem
        });
      }

      // 重置表单
      this.newItem = {
        userId: '',
        tag: '科技',
        percentage: ''
      };
    },
    editItem(item) {
      this.newItem = {
        userId: item.userId,
        tag: item.tag,
        percentage: item.percentage
      };
      this.editingId = item.id;
    },
    async deleteItem(id) {
      try {
        const response = await Service.delete(`/api/userFlavor/deleteUserFlavorById`,{
          params: { id: id }
        })
        if (response.status === "success") {
          ElMessage.success('删除成功')
          this.loadData() // 重新加载数据
        } else {
          ElMessage.error(response.info || '删除失败')
        }
      } catch (error) {
        const errorMsg = error.response?.data?.info 
          || error.response?.data?.message 
          || error.message 
          || '请求异常'
        ElMessage.error(errorMsg)
      }
    },
    sortByPercentage() {
      this.sortAscending = !this.sortAscending;
    },
    getPercentageClass(percentage) {
      const value = parseInt(percentage);
      if (value >= 80) return 'high';
      if (value >= 60) return 'medium';
      return 'low';
    }
  }
}

</script>

<style scoped>
.display-chart-container {
  display: flex;
  min-height: 100vh;
  background: linear-gradient(135deg, #b6e0ff 0%, #f7d9ff 100%);
}

.user-preferences {
  flex: 1;
  padding: 20px;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.8) 0%, rgba(240, 248, 255, 0.8) 100%);
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  margin-left: 220px;
}

h1 {
  color: #495057;
  font-size: 22px;
  font-weight: 600;
  background: -webkit-linear-gradient(135deg, #409eff, #ff69b4);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.05);
  text-align: left;
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
}
.header-card {
  margin-bottom: 20px;
  border-radius: 12px;
  border: none;
  background: linear-gradient(135deg, #d9efff 0%, #f7d9ff 100%);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.add-button {
  padding: 10px 20px;
  font-weight: 500;
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.3);
  background: linear-gradient(135deg, #73a6ff 0%, #ff69b4 100%);
  border: none;
  transition: all 0.3s ease;
  color: white;
  border-radius: 4px;
  text-decoration: none;
  font-size: 14px;
}

.add-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.4);
}

.control-panel {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  align-items: center;
}

.search-input, .tag-filter {
  padding: 10px 15px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  background-color: #fff;
  transition: border-color 0.2s;
}

.search-input:focus, .tag-filter:focus {
  border-color: #409eff;
  outline: none;
}

.search-input {
  flex: 1;
}

.sort-btn {
  padding: 10px 20px;
  font-weight: 500;
  box-shadow: 0 2px 6px rgba(64, 158, 255, 0.3);
  background: linear-gradient(135deg, #73a6ff 0%, #ff69b4 100%);
  border: none;
  transition: all 0.3s ease;
  color: white;
  border-radius: 4px;
  cursor: pointer;
}

.sort-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(64, 158, 255, 0.4);
}

.table-container {
  margin-bottom: 30px;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(240, 248, 255, 0.9) 100%);
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.06);
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
}

th {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}

tr:hover {
  background-color: #f5f7fa;
}

.percentage-bar-container {
  position: relative;
  height: 24px;
  background-color: #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
}

.percentage-bar {
  height: 100%;
  transition: width 0.3s;
}

.percentage-text {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  color: #333;
  font-size: 12px;
}

.high {
  background-color: #67c23a;
}

.medium {
  background-color: #e6a23c;
}

.low {
  background-color: #f56c6c;
}

.action-buttons {
  display: flex;
  gap: 8px;
}

.edit-btn, .delete-btn, .detail-btn {
  padding: 8px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  border: none;
  transition: all 0.2s ease;
}

.edit-btn {
  background: linear-gradient(135deg, #d9efff 0%, #f7d9ff 100%);
  color: #5c940d;
  border: 1px solid #d3e9a6;
}

.edit-btn:hover {
  background: linear-gradient(135deg, #ebfbee 0%, #f7d9ff 100%);
}

.delete-btn {
  background: linear-gradient(135deg, #fff5f5 0%, #f7d9ff 100%);
  color: #e03131;
  border: 1px solid #ffc9c9;
}

.delete-btn:hover {
  background: linear-gradient(135deg, #ffe3e3 0%, #f7d9ff 100%);
}

.detail-btn {
  background: linear-gradient(135deg, #f0f9eb 0%, #f7d9ff 100%);
  color: #67c23a;
  border: 1px solid #e1f3d8;
  text-decoration: none;
  display: inline-block;
}

.detail-btn:hover {
  background: linear-gradient(135deg, #e1f3d8 0%, #f7d9ff 100%);
}

.chart-container {
  margin-top: 30px;
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.9) 0%, rgba(240, 248, 255, 0.9) 100%);
  border-radius: 8px;
  padding: 15px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.06);
}

.chart {
  display: flex;
  height: 200px;
  align-items: flex-end;
  gap: 20px;
  padding-top: 20px;
}

.chart-bar {
  flex: 1;
  background: linear-gradient(135deg, #73a6ff 0%, #ff69b4 100%);
  position: relative;
  min-width: 40px;
  transition: height 0.5s;
  border-radius: 4px 4px 0 0;
}

.chart-label {
  position: absolute;
  bottom: -25px;
  left: 50%;
  transform: translateX(-50%);
  white-space: nowrap;
  font-size: 12px;
  color: #606266;
}
</style>

mounted() {
  this.loadData();
}